#!/bin/bash

#
# pdfroteven -- by Dario Berzano <dario.berzano@gmail.com>
#
# Part of the lfscripts suite -- http://lfscripts.googecode.com/
#
# Uses pdfinfo and pdftk to rotate upside-down (180 degrees) even pages of a PDF
# document. It is used, for instance, to print front-rear on printer whose
# configurations do not allow you to bind the documents on the desired edge.
#

#
# Functions
#

export PDFINFO
export PDFTK

# Check for required software
function CheckSw() {

  # Search for pdfinfo
  PDFINFO=`which pdfinfo`
  [ $? != 0 ] && PDFINFO=""

  # Search for pdftk
  PDFTK=`which pdftk`
  [ $? != 0 ] && PDFTK=""

  # Errors
  [ "$PDFINFO" == "" ] && echo "pdfinfo not found"
  [ "$PDFTK" == "" ] && echo "pdftk not found"

  if [ "$PDFINFO" == "" ] || [ "$PDFTK" == "" ]; then
    return 1
  fi

}

# Main function
function Main() {

  # Check if software is present, elsewhere abort
  CheckSw || exit 1

  local INPUT="$1"
  local PAGES=$("$PDFINFO" "$INPUT" 2> /dev/null | grep Pages: | cut -b7-)
  if [ "$PAGES" == "" ]; then
    echo "Cannot find the specified file or corrupted file: $INPUT"
    exit 2
  fi

  # Form the rotate page command string for pdftk
  local STR=""
  for (( i=1; $i<=$PAGES; i++ ));
  do
    let r=i%2
    if [ $r == "0" ]; then
      STR="$STR ${i}D"
    else
      STR="$STR $i"
    fi
  done

  # Output file: append -roteven to the filename
  local OUTPUT=${1/%\.pdf/-roteven.pdf}
  if [ "$OUTPUT" == "$INPUT" ]; then
    OUTPUT="${INPUT}-roteven.pdf"
  fi

  "$PDFTK" "$INPUT" cat $STR output "$OUTPUT"

  echo "File $OUTPUT written with even pages rotated upside-down."
}

#
# Entry point
#

Main "$@"
